<template>
  <div class="menu-tree-box w-full h-full overflow-hidden overflow-y-auto box-border">
    <a-tree
      v-if="props.account && treeShow"
      :default-expanded-keys="defaultExpendKeys"
      blockNode
      checkable
      multiple
      :check-strictly="true"
      checked-strategy="all"
      :checked-keys="nodeChecked"
      :field-names="{
        key: 'code',
        children: 'children',
        title: 'org_name',
      }"
      :data="treeHandlered"
      @check="(ckeck as any)"
    >
      <template #title="{org_name}">
        <span  class="" style="
        font-family: Microsoft YaHei;
        font-size: 14px;
        font-weight: normal;
        color: #465A80;
        ">{{ org_name }}</span>
      </template>
    </a-tree>
  </div>
</template>

<script lang="ts" setup>
import { watch, onMounted, ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import * as User from '@/api/user';
import * as Org from '@/api/org';
import { Message } from '@arco-design/web-vue';
import { getTreeData } from './values';

const props = defineProps({
  account: {
    type: String,
    default: ''
  },
  roleId: {
    type: Number,
    default: undefined
  },
  disChecked: {
    type: Boolean,
    default: false
  }
})
const emits = defineEmits(['checked'])
const treeHandlered = ref<any[]>([])
const menuArr = ref<any[]>([])
const nodeChecked = ref<any[]>([])
const defaultExpendKeys = ref<any[]>([])
const treeShow = ref(false)


function ckeck(checked: number[], node: any) {
  nodeChecked.value = [...checked]
  emits('checked', [...checked])
}



// 获取系统菜单树
function GetTreeData() {
  Org.getOrgTreeList().then(res => {
    if(res.code && res.data) {
      menuArr.value = getTreeData(res.data.children)
      menuArr.value.forEach(item => {
        item.disabled = props.disChecked
        defaultExpendKeys.value.push(item.code)
      })
      treeHandlered.value = [...res.data.children]
      treeShow.value = true
      return
    }
    Message.error('获取系统树数据失败')
  })
}

function getRoleOrgs() {
  if(props.roleId) {
    User.getRoleOrg(props.roleId).then(res => {
      if(res.code && res.data) {
        nodeChecked.value = res.data.map((item: any) => item.org_code)
         emits('checked', [...nodeChecked.value])
      }
    })
  }
}

watch(() => props.roleId, (val) => {
  if(val) {
    // 获取用户已有的菜单权限
    getRoleOrgs()
  } else {
    nodeChecked.value = []
  }
})

onMounted(() => {
  // 获得系统菜单
  GetTreeData()
})
</script>

<style lang="less" scoped>

</style>
